package org.hitchhike.core.service;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.hitchhike.common.service.BaseService;
import org.hitchhike.core.domain.User;
import org.hitchhike.core.enums.Constant;
import org.hitchhike.core.enums.UserStateEnum;
import org.hitchhike.core.exception.JsonException;
import org.hitchhike.core.repository.UserRepository;
import org.hitchhike.core.utils.PageableUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

@Service
public class UserService extends BaseService<User, Long> {

  String image =
      "";

  @Autowired
  private UserRepository getUserRepository() {
    return (UserRepository) baseRepository;
  }

  @Override
  public User save(User user) {
    if (user.getUserType() == Constant.TYPE_0) {
      user.setUserState(UserStateEnum.ENABLED);
    } else if (user.getUserType() == Constant.TYPE_1) {
      user.setUserState(UserStateEnum.ENABLED);
    } else if (user.getUserType() == Constant.TYPE_2) {
      user.setUserState(UserStateEnum.PENDING);
    } else {
      user.setUserState(UserStateEnum.DISABLED);
    }

    try {
      user.setImage(image.getBytes("UTF-8"));
      return super.save(user);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public User update(User user) {
    if (user.getId() == null) {
      throw new JsonException("用户不存在");
    }
    return super.update(user);
  }

  public List<User> findPassenger() {
    return getUserRepository().findByUserType(Constant.TYPE_1);
  }

  public User findByUsername(String username) {
    return getUserRepository().findByUsername(username);
  }

  public Page<User> findPageDriver(Integer page) {
    return getUserRepository().findPageByUserType(Constant.TYPE_2,
        PageableUtil.getPageable(page, 10));
  }

  public Page<User> findPagePassenger(Integer page) {
    return getUserRepository().findPageByUserType(Constant.TYPE_1,
        PageableUtil.getPageable(page, 10));
  }

}
